<script setup name="task">
import { ref, shallowRef, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';

import { ElDialog, ElTable, ElTableColumn, ElPagination, ElSelect, ElOption, ElMessage } from 'element-plus';
import { Search, Plus, Calendar } from '@element-plus/icons-vue';

import calendar from '@/views/calendar.vue';
import service from '@/utils/request';
import getUniqueId from '@/utils/getUniqueId';

const router = useRouter();

// 搜索框相关变量
const searchValue = ref('');

// 表格数据相关变量
const pageNum = shallowRef(1);
const pageSize = shallowRef(5);
const totalSize = shallowRef(0);
const tableData = ref([]);
const currentExpandedRow = ref([]);
const searchRef = ref(null);

// 新建任务相关变量
const isShowCreateTask = shallowRef(false);
const isShowCalendar = shallowRef(false);
const selectedTaskDate = shallowRef('');
const createTaskData = reactive({
  name: '',
  academicName: '',
  academicEndTime: '结束时间',
  academicStartTime: '开始时间',
  baseWorkName: '',
  baseWorkEndTime: '结束时间',
  baseWorkStartTime: '开始时间',
});

// 处理表格数据
const fixedTableData = (list) => {
  return list.map((item) => {
    const academicWorkSituation = item.children.academicWorkSituation;
    const baseWorkSituation = item.children.baseWorkSituation;
    
    const temp = [
      {
        id: academicWorkSituation.academicWorkId + getUniqueId() + 'academicWork',
        name: academicWorkSituation.academicWorkName,
        state: academicWorkSituation.academicWorkState,
        startTime: academicWorkSituation.academicWorkStartTime.join('.').substring(0, 10),
        endTime: academicWorkSituation.academicWorkEndTime.join('.').substring(0, 10),
        operation: '详情'
      },
      {
        id: baseWorkSituation.baseWorkId + getUniqueId() + 'baseWork',
        name: baseWorkSituation.baseWorkName,
        state: baseWorkSituation.baseWorkState,
        startTime: baseWorkSituation.baseWorkStartTime.join('.').substring(0, 10),
        endTime: baseWorkSituation.baseWorkEndTime.join('.').substring(0, 10),
        operation: '详情'
      }
    ];
    
    return {
      id: item.id + getUniqueId(),
      name: item.name,
      state: item.state,
      children: temp
    };
  });
};

// 查询任务列表
const getTableData = (key) => {
  service({
    method: 'post',
    url: '/superadmin/exam/get',
    params: {
      condition: key,
      pageNum: pageNum.value,
      pageSize: pageSize.value,
    },
    data: {},
    headers: {
      Authorization: 'Bearer ' + localStorage.getItem('token'),
    },
  }).then((res) => {
    //console.log(res.data.list);
    tableData.value = fixedTableData(res.data.list);
    totalSize.value = res.data.total || 0;
  }).catch(() => {
    ElMessage({
      message: '获取数据失败',
      type: 'error',
    });
    tableData.value = [];
    totalSize.value = 0;
  });
};

// 限制只展开一行
const handleExpandChange = (row, expandedRows) => {
  currentExpandedRow.value = expandedRows.length ? row.id : null;
};

// 点击行展开
const rowClickExpand = (row) => {
  currentExpandedRow.value = row.id;
};

// 搜索
const searchChange = () => {
  getTableData(searchValue.value);
};


//处理创建任务提交事件
const handleCreateTaskSubmit = () => {
  // 验证表单数据
  if (!createTaskData.name || !createTaskData.academicName || !createTaskData.academicEndTime || !createTaskData.academicStartTime || !createTaskData.baseWorkName || !createTaskData.baseWorkEndTime || !createTaskData.baseWorkStartTime) {
    ElMessage({
      message: '请填写完整任务信息',
      type: 'warning',
    });
    return;
  }
  // 发送创建任务请求
  service({
    method: 'post',
    url: '/superadmin/exam/add',
    data: createTaskData,
    headers: {
      Authorization: 'Bearer ' + localStorage.getItem('token'),
    },
  }).then((res) => {
    if (res.message === '请求正常') {
      ElMessage({
        message: '创建任务成功',
        type: 'success',
      });
    } else {
      ElMessage({
        message: '创建任务失败',
        type: 'error',
      });
    }
    // 关闭弹窗并刷新任务列表
    handleCreateTaskCancel();
    getTableData(searchValue.value);
  }).catch(() => {
    ElMessage({
      message: '创建任务失败',
      type: 'error',
    });
  });
};
// 处理创建任务取消事件
const handleCreateTaskCancel = () => {
  isShowCreateTask.value = false;
  Object.keys(createTaskData).forEach(key => {
    createTaskData[key] = '';
  });
};

// 日历相关事件
const showCalendar = (value) => {
  selectedTaskDate.value = value;
  isShowCalendar.value = true;
};

const updateSelection = (date) => {
  if (selectedTaskDate.value === 'study') {
    createTaskData.academicStartTime = date.startDate || '开始日期';
    createTaskData.academicEndTime = date.endDate || '结束日期';
  }
  if (selectedTaskDate.value === 'baseWork') {
    createTaskData.baseWorkStartTime = date.startDate || '开始日期';
    createTaskData.baseWorkEndTime = date.endDate || '结束日期';
  }
  isShowCalendar.value = false;
};

//处理日历弹窗取消事件
const handleCalendarCancel = () => {
  isShowCalendar.value = false;
  // 重置 selectedTaskDate 确保可以再次打开弹窗
  selectedTaskDate.value = '';
};

//处理日历弹窗关闭事件（点击关闭按钮或背景）
const handleCalendarClose = () => {
  isShowCalendar.value = false;
  // 重置 selectedTaskDate 确保可以再次打开弹窗
  selectedTaskDate.value = '';
};


// 表格操作
const operationClick = (row, column) => {
  if (column.property !== 'operation') return;
  
  if (row.id.includes('academicWork')) {
    router.push({
      path: '/superAdministrator/task/studyDetail',
      query: row
    });
  }
  if (row.id.includes('baseWork')) {
    router.push({
      path: '/superAdministrator/task/baseWorkDetail',
      query: row
    });
  }
};

// 分页器相关事件
const handleSizeChange = (data) => {
  pageNum.value = data;
  getTableData(searchValue.value);
};

// 组件挂载钩子
onMounted(() => {
  getTableData('');
});
</script>

<template>
  <!-- 日历对话框 -->
  <el-dialog
    :model-value="isShowCalendar"
    width="650px"
    top="20vh"
    draggable
    destroy-on-close
    :show-close="false"
    :close-on-click-modal="true"
    @close="handleCalendarClose"
  >
    <template #default>
      <calendar
        @cancel="handleCalendarCancel"
        @update="updateSelection"
      />
    </template>
  </el-dialog>
  
  <!-- 新建任务对话框 -->
    <el-dialog
    v-model="isShowCreateTask"
    width="650px"
    top="20vh"
    :show-close="false"
    class="create-task-dialog"
    draggable
    destroy-on-close
    :close-on-click-modal="true"
    >
    <template #header>
        <div class="createTaskTitle">
        <span>新建任务</span>
        </div>
    </template>
    <template #default>
        <div class="createTaskContent">
        <div class="form-group taskName">
            <label class="form-label">任务名称</label>
            <input 
            type="text" 
            placeholder="请输入任务名称" 
            v-model="createTaskData.name"
            class="form-input"
            />
        </div>
        <div class="form-row form-row-first">
            <div class="form-group">
            <label class="form-label">学业情况任务名称</label>
            <input 
                type="text" 
                placeholder="请输入" 
                v-model="createTaskData.academicName"
                class="form-input"
            />
            </div>
            <div class="form-group">
            <label class="form-label">基础工作任务名称</label>
            <input 
                type="text" 
                placeholder="请输入" 
                v-model="createTaskData.baseWorkName"
                class="form-input"
            />  
            </div>
        </div>
        <div class="form-row">
            <div class="form-group">
            <label class="form-label">学业任务时间</label>
            <div class="calendar-wrapper" @click="showCalendar('study')">
                <div class="calendar">
                <span class="date-text">{{ createTaskData.academicStartTime || '开始时间' }}</span>
                <span class="date-separator">至</span>
                <span class="date-text">{{ createTaskData.academicEndTime || '结束时间' }}</span>
                </div>
                <el-icon class="calendar-icon"><Calendar /></el-icon>
            </div>
            </div>
            <div class="form-group">
            <label class="form-label">基础任务时间</label>
            <div class="calendar-wrapper" @click="showCalendar('baseWork')">
                <div class="calendar">
                <span class="date-text">{{ createTaskData.baseWorkStartTime || '开始时间' }}</span>
                <span class="date-separator">至</span>
                <span class="date-text">{{ createTaskData.baseWorkEndTime || '结束时间' }}</span>
                </div>
                <el-icon class="calendar-icon"><Calendar /></el-icon>
            </div>
            </div>
        </div>
        </div>
    </template>
    <template #footer>
        <div class="createTaskFooter">
        <div class="cancel-btn" @click="handleCreateTaskCancel">取消</div>
        <div class="submit-btn" @click="handleCreateTaskSubmit">创建任务</div>
        </div>
    </template>
    </el-dialog>
  
  <!-- 任务发布组件内容 -->
  <div class="task">
    <!-- 任务发布标题 -->
    <div class="header">
      <span>任务发布</span>
    </div>
    <!-- 数据表格 -->
    <div class="content">
      <div class="dataTable">
        <div class="tableHeader">
          <div class="left">
            <span>学业导师考核任务发布</span>
          </div>
          <div class="right">
            <div class="search" ref="searchRef">
              <input v-model.trim="searchValue" type="text" placeholder="搜索" @change.enter="searchChange" />
              <el-icon class="icon"><Search /></el-icon>
            </div>
            <div class="createTask" @click="isShowCreateTask = true">
              <span>新建任务</span>
              <el-icon><Plus /></el-icon>
            </div>
          </div>
        </div>
        
        <!-- 数据表格 -->
        <div class="tableContent">
          <el-table
            :data="tableData"
            row-key="id"
            :style="{ width: '100%' }"
            height="100%"
            show-overflow-tooltip
            :header-cell-style="{ color: '#000', background: '#f2f3f5' }"
            empty-text="暂无数据"
            @cell-click="operationClick"
            :expand-row-keys="[currentExpandedRow]"
            @expand-change="handleExpandChange"
            @row-click="rowClickExpand"
          >
            <el-table-column prop="name" label="任务标题" />
            <el-table-column align="center" prop="state" label="任务状态" width="100">
              <template #default="scope">
                <span :class="`state-${scope.row.state}`">{{ scope.row.state }}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="startTime" label="开始时间" width="150" />
            <el-table-column align="center" prop="endTime" label="结束时间" width="150" />
            <el-table-column align="center" prop="operation" label="操作" width="100" fixed="right">
              <template #default="scope">
                <span class="operation-link">{{ scope.row.operation }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <!-- 底部分页器 -->
        <div class="tableFooter">
          <div class="left">
            <div class="total">共计: {{ totalSize }} 条</div>
          </div>
          <div class="right">
            <div class="pagination">
              <el-pagination
                layout="prev, pager, next"
                :total="totalSize"
                :page-size="pageSize"
                background
                size="small"
                @current-change="handleSizeChange"
              />
            </div>
            <div class="selector">
              <el-select
                v-model="pageSize"
                placeholder="每页条数"
                style="width: 80px"
                size="small"
                @change="getTableData(searchValue)"
              >
                <el-option label="5条/页" :value="5" selected />
                <el-option label="10条/页" :value="10" />
                <el-option label="20条/页" :value="20" />
              </el-select>
            </div>
            <div class="jump">
              <span class="title">前往:</span>
              <input type="text" v-model="pageNum" @change="getTableData(searchValue)" />
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
@use "sass:color";

// 颜色变量
$primary-color: #4c6fb4;
$danger-color: #eb5757;
$danger-hover: #ff6b6b;
$gray-color: #909399;
$gray-hover: #a0a2a5;
$bg-light: #f1f2f3;
$bg-lighter: #f2f3f5;
$border-color: #cacacb;
$text-primary: #000000;
$text-secondary: #86909c;
$text-tertiary: #8e96a0;
$success-color: #00af1d;
$inactive-color: #898989;

// 创建任务对话框
.create-task-dialog {
  .el-dialog__body {
    padding: 30px;
  }
}

.createTaskTitle {
  font-size: 18px;
  font-weight: 600;
  color: $text-primary;
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 10px;
}

.createTaskContent {
  padding: 10px 0;
  
  .form-group {
    margin-bottom: 24px;
    &.taskName {
      width: 100%;
    }
  }
  .form-row {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;
    .form-group {
      margin-bottom: 0px;
    }
  }
  .form-row-first {
    margin-bottom: 24px;
  }
  .form-label {
    display: block;
    margin-bottom: 8px;
    font-size: 14px;
    font-weight: 500;
    color: $text-primary;
    position: relative;
    padding-left: 10px;
    
    &::before {
      content: '*';
      position: absolute;
      left: 0;
      color: $danger-color;
    }
  }
  
  .form-input {
    width: 100%;
    height: 40px;
    border: 1px solid $border-color;
    border-radius: 6px;
    padding: 0 12px;
    font-size: 14px;
    color: $text-primary;
    background-color: #fff;
    transition: all 0.3s ease;
    
    &:focus {
      outline: none;
      border-color: $primary-color;
      box-shadow: 0 0 0 1px color.adjust($primary-color, $alpha: 0.1);
    }
    
    &::placeholder {
      color: $text-tertiary;
    }
  }
  
  .calendar-wrapper {
    position: relative;
    
    .calendar {
      width: 100%;
      height: 40px;
      border: 1px solid $border-color;
      border-radius: 6px;
      padding: 0 40px 0 12px;
      display: flex;
      align-items: center;
      cursor: pointer;
      background-color: #fff;
      transition: all 0.3s ease;
      
      &:hover {
        border-color: $primary-color;
      }
      
      .date-text {
        color: $text-primary;
        font-size: 14px;
        max-width: calc(50% - 10px);
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      
      .date-separator {
        margin: 0 8px;
        color: $text-tertiary;
      }
    }
    
    .calendar-icon {
      position: absolute;
      right: 12px;
      top: 50%;
      transform: translateY(-50%);
      color: $text-tertiary;
      cursor: pointer;
      font-size: 18px;
    }
  }
}

.createTaskFooter {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px 0 0;
  
  .cancel-btn,
  .submit-btn {
    padding: 8px 20px;
    border-radius: 6px;
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.3s ease;
    
    &:active {
      transform: scale(0.98);
    }
  }
  
  .cancel-btn {
    background-color: #f5f7fa;
    color: $text-secondary;
    border: 1px solid $border-color;
    
    &:hover {
      background-color: #eef2f7;
      color: $text-primary;
    }
  }
  
  .submit-btn {
    background-color: $primary-color;
    color: #fff;
    
    &:hover {
      background-color: color.adjust($primary-color, $lightness: -5%);
      box-shadow: 0 2px 8px color.adjust($primary-color, $alpha: 0.3);
    }
  }
}

// 任务发布组件内容
.task {
  width: 100%;
  height: 100%;
  font-weight: 500;
  
  .header {
    height: 60px;
    padding-left: 20px;
    display: flex;
    align-items: center;
    border-top: 1px solid $border-color;
    border-bottom: 1px solid $border-color;
    background-color: white;
    font-size: 23px;
    color: $text-primary;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  }
  
  .content {
    width: calc(100% - 60px);
    height: 90%;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 20px;
    background-color: #f7f8fa;
    .dataTable {
      width: 100%;
      height: 100%;
      background-color: #ffffff;
      border-radius: 8px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
      overflow: hidden;
      .tableHeader {
        width: 100%;
        height: 10%;
        padding: 0 20px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        border-bottom: 1px solid #f0f0f0;
        
        .left {
          width: 200px;
          font-size: 20px;
          font-weight: 600;
          color: $text-primary;
        }
        
        .right {
          width: calc(100% - 200px);
          display: flex;
          justify-content: flex-end;
          gap: 15px;
          
          .search {
            width: 20vw;
            height: 4vh;
            display: flex;
            align-items: center;
            border-radius: 6px;
            background-color: $bg-light;
            transition: all 0.3s ease;
            
            &:hover {
              background-color: #e0e1e2;
            }
            
            &:focus-within {
              outline: 2px solid $primary-color;
              background-color: #ffffff !important;
              box-shadow: 0 0 0 3px rgba($primary-color, 0.1);
            }
            
            input {
              height: 100%;
              width: 90%;
              outline: none;
              border: none;
              background-color: transparent;
              text-indent: 1em;
              color: $text-primary;
            }
            
            .icon {
              width: 10%;
              height: 100%;
              display: flex;
              align-items: center;
              justify-content: center;
              cursor: pointer;
              color: $text-tertiary;
              
              &:hover {
                color: $primary-color;
              }
            }
          }
          
          .createTask {
            width: 100px;
            height: 4vh;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 5px;
            border-radius: 6px;
            background-color: #4c6fbc;
            color: white;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            
            &:hover {
              background-color: #4c6fb4;
              transform: translateY(-1px);
              box-shadow: 0 2px 8px color.adjust($primary-color, $alpha: 0.3);
            }
          }
        }
      }
      
      .tableContent {
        width: 100%;
        height: 80%;
        padding: 0 20px;
        
        .state-已结束 {
          color: $inactive-color;
        }
        
        .state-进行中 {
          color: $success-color;
        }
        
        .operation-link {
          color: $primary-color;
          cursor: pointer;
          transition: all 0.3s ease;
          
          &:hover {
            color: #2c6df9;
            text-decoration: underline;
          }
        }
      }
      
      .tableFooter {
        width: 100%;
        height: 10%;
        padding: 0 20px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        border-top: 1px solid #f0f0f0;
        
        .left {
          font-size: 12px;
          color: $text-secondary;
        }
        
        .right {
          display: flex;
          align-items: center;
          gap: 15px;
          
          .jump {
            display: flex;
            align-items: center;
            
            .title {
              margin-right: 5px;
              font-size: 12px;
              color: $text-secondary;
            }
            
            input {
              width: 40px;
              height: 28px;
              text-align: center;
              line-height: 28px;
              border: 1px solid #dcdfe6;
              outline: none;
              border-radius: 4px;
              background-color: #ffffff;
              color: $text-secondary;
              transition: all 0.3s ease;
              
              &:focus {
                border-color: $primary-color;
                color: $text-primary;
                box-shadow: 0 0 0 2px color.adjust($primary-color, $alpha: 0.1);
              }
            }
          }
        }
      }
    }
  }
}
</style>